﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using Microsoft.Win32;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Text;
using System.Text.RegularExpressions;

namespace PieterBasIJdens.PBsVSUtils
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// 
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the 
    /// IVsPackage interface and uses the registration attributes defined in the framework to 
    /// register itself and its components with the shell.
    /// </summary>
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
    [ProvideMenuResource("Menus.ctmenu", 1)]
    [Guid(GuidList.guidPBsVSUtilsPkgString)]
    public sealed class PBsVSUtilsPackage : Package
    {
        /// <summary>
        /// Default constructor of the package.
        /// Inside this method you can place any initialization code that does not require 
        /// any Visual Studio service because at this point the package object is created but 
        /// not sited yet inside Visual Studio environment. The place to do all the other 
        /// initialization is the Initialize method.
        /// </summary>
        public PBsVSUtilsPackage()
        {
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
        }



        /////////////////////////////////////////////////////////////////////////////
        // Overridden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (null != mcs)
            {
                CommandID menuCommandID;
                MenuCommand menuItem;

                // Create the command for the menu item.
                menuCommandID = new CommandID(GuidList.guidPBsVSUtilsCmdSet, (int)PkgCmdIDList.cmdidCreateMSIIdentifier);
                menuItem = new MenuCommand(CreateMSIIDCallback, menuCommandID);
                mcs.AddCommand(menuItem);

                // Create the command for the menu item.
                menuCommandID = new CommandID(GuidList.guidPBsVSUtilsCmdSet, (int)PkgCmdIDList.cmdidCreateMSIGuid);
                menuItem = new MenuCommand(CreateMSGUIDCallback, menuCommandID);
                mcs.AddCommand(menuItem);

            }
        }
        #endregion


        /// <summary>
        /// Replaces the current selection with a new MSI ID.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        private void CreateMSIIDCallback(object sender, EventArgs e)
        {
            ReplaceSelectedText(() => String.Format("id{0}", System.Text.RegularExpressions.Regex.Replace(Guid.NewGuid().ToString("D"),
                            "[^A-Za-z0-9]", "").ToUpper()));
        }

        /// <summary>
        /// Replaces the current selection with a GUID.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        private void CreateMSGUIDCallback(object sender, EventArgs e)
        {
            ReplaceSelectedText(() => Guid.NewGuid().ToString("D").ToUpper());
        }

        private void ReplaceSelectedText(Func<String> replacement)
        {
            IWpfTextViewHost viewHost = GetCurrentViewHost();
            if (null != viewHost)
            {
                ITextSelection selection = GetSelection(viewHost);

                if (null != selection)
                {
                    var textView = selection.TextView;

                    var edit = textView.TextBuffer.CreateEdit();

                    for (int index = selection.SelectedSpans.Count - 1; index >= 0; index--)
                    {
                        var span = selection.SelectedSpans[index];
                        String id = replacement();
                        edit.Replace(span, id);
                    }

                    edit.Apply();
                }
            }
        }

        IWpfTextViewHost GetCurrentViewHost()
        {
            // code to get access to the editor's currently selected text cribbed from
            // http://msdn.microsoft.com/en-us/library/dd884850.aspx
            IVsTextManager txtMgr = (IVsTextManager)GetService(typeof(SVsTextManager));
            IVsTextView vTextView = null;
            int mustHaveFocus = 1;
            txtMgr.GetActiveView(mustHaveFocus, null, out vTextView);
            IVsUserData userData = vTextView as IVsUserData;
            if (userData == null)
            {
                return null;
            }
            else
            {
                IWpfTextViewHost viewHost;
                object holder;
                Guid guidViewHost = DefGuidList.guidIWpfTextViewHost;
                userData.GetData(ref guidViewHost, out holder);
                viewHost = (IWpfTextViewHost)holder;
                return viewHost;
            }
        }


        /// Given an IWpfTextViewHost representing the currently selected editor pane,
        /// return the ITextDocument for that view. That's useful for learning things 
        /// like the filename of the document, its creation date, and so on.
        ITextDocument GetTextDocumentForView(IWpfTextViewHost viewHost)
        {
            ITextDocument document = null;
            viewHost.TextView.TextDataModel.DocumentBuffer.Properties.TryGetProperty(typeof(ITextDocument), out document);
            return document;
        }

        /// Get the current editor selection
        ITextSelection GetSelection(IWpfTextViewHost viewHost)
        {
            return viewHost.TextView.Selection;
        }
    }
}
